import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/app/prisma/client';
import { GroupRole } from '@prisma/client';
import getUserId from '@/utils/getUserId';

export async function POST(req: NextRequest, { params }: { params: { groupId: string } }) {
  try {
    const inviterId = getUserId(req);
    if (!inviterId) {
      return NextResponse.json({ error: '请先登录' }, { status: 401 });
    }

    const { groupId } = params;
    const { inviteeId } = await req.json();

    if (!inviteeId) {
      return NextResponse.json({ error: '缺少被邀请人ID (inviteeId)' }, { status: 400 });
    }

    // 1. 验证邀请人是否是群成员 (简化逻辑，实际可改为仅群主/管理员可邀请)
    const inviterMembership = await prisma.groupMember.findUnique({
      where: {
        groupId_userId: {
          groupId,
          userId: inviterId,
        },
      },
    });

    if (!inviterMembership) {
      return NextResponse.json({ error: '你不在该群组中，无权邀请' }, { status: 403 });
    }

    // 2. 验证被邀请人是否存在
    const inviteeExists = await prisma.user.findUnique({ where: { id: inviteeId } });
    if (!inviteeExists) {
      return NextResponse.json({ error: '被邀请的用户不存在' }, { status: 404 });
    }
    
    // 3. 验证被邀请人是否已在群组中
    const inviteeMembership = await prisma.groupMember.findUnique({
      where: {
        groupId_userId: {
          groupId,
          userId: inviteeId,
        },
      },
    });

    if (inviteeMembership) {
      return NextResponse.json({ error: '该用户已在群组中' }, { status: 400 });
    }

    // 4. 添加新成员
    const newMember = await prisma.groupMember.create({
      data: {
        groupId,
        userId: inviteeId,
        role: GroupRole.MEMBER, // 默认为普通成员
      },
    });

    return NextResponse.json({ message: '成员添加成功', member: newMember }, { status: 201 });
  } catch (error) {
    console.error('添加群成员失败:', error);
    return NextResponse.json({ error: '服务器错误' }, { status: 500 });
  }
}

export async function GET(req: NextRequest, { params }: { params: { groupId: string } }) {
  try {
    const { groupId } = params;
    const members = await prisma.groupMember.findMany({
      where: { groupId },
      include: {
        user: {
          select: {
            id: true,
            username: true,
            avatar: true,
          }
        }
      },
      orderBy: {
        joinedAt: 'asc',
      }
    });

    const formattedMembers = members.map(m => ({
      ...m.user,
      role: m.role,
      joinedAt: m.joinedAt,
    }));

    return NextResponse.json(formattedMembers);
  } catch (error) {
    console.error('获取群成员列表失败:', error);
    return NextResponse.json({ error: '服务器错误' }, { status: 500 });
  }
} 